#!/usr/bin/env python
# _*_ coding: utf-8 _*_

import re

from ElementSoup import parse, ET

AMAZON_ISBN = u"http://www.amazon.com/gp/product/%s?ie=UTF8&tag=taet-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=%s"
AMAZON_SEARCH = u"http://www.amazon.com/gp/search?ie=UTF8&keywords=%s&tag=taet-20&index=blended&linkCode=ur2&camp=1789&creative=9325"
GOOGLE_SEARCH = u"http://www.google.com/search?q=%s&ie=utf-8&oe=utf-8&btnI=I'm+Feeling+Lucky"


def _link_isbn(m):
    isbn = m.group(1).replace('-', '')
    return AMAZON_ISBN % (isbn, isbn)


def _link_amazon(m):
    keywords = m.group(1)
    return AMAZON_SEARCH % keywords


def _link_google(m):
    keywords = m.group(1)
    return GOOGLE_SEARCH % keywords


def beautify(s):
    repls = [   
                (ur'"\b(.*?)\b"',           lambda m: u'“%s”' % m.group(1)),
                (ur'(^|\s)"(.*?)"(\s|$)',   lambda m: u'“%s”' % m.group(2)),
                (u'--',                     u'—'),
                (u'-',                      u'–'),
            ]
    for repl, func in repls:
        s = re.sub(repl, func, s)
    return s


def linkify(s):
    repls = [   
                (u'^amazon:(.*)$',          _link_amazon),
                (u'^isbn:(.*)$',            _link_isbn),
                (u'^google:(.*)$',          _link_google),
            ]
    for repl, func in repls:
        s = re.sub(repl, func, s)
    return s


def lesstile(fp):
    tree = parse(fp)
    for el in tree.getiterator():
        if el.text: el.text = beautify(el.text)
        if el.tail: el.tail = beautify(el.tail)
        if el.attrib.get('href'): el.attrib['href'] = linkify(el.attrib['href'])
    return ET.tostring(tree)
    

if __name__ == '__main__':
    import sys
    out = lesstile(sys.stdin)
    sys.stdout.write(out)
